import '../utils/sp_util.dart';
import '../index.dart'; // 假设AssetsImages在index.dart中
import 'dart:math';

class PerfumeService {
  static const String perfumeListKey = 'perfume_list';

  /// 初始化十二条香水数据
  static Future<void> initDefaultPerfumes() async {
    List<UserModel> users = UserService.getAllUsers();
    Random random = Random();
    List<String> categories = ['Strong fragrance', 'Eau de Toilette', 'Woody'];

    // 按分类组织图片
    Map<String, List<String>> categoryImages = {
      'Strong fragrance': [
        AssetsImages.strong1,
        AssetsImages.strong2,
        AssetsImages.strong3,
        AssetsImages.strong4,
      ],
      'Eau de Toilette': [
        AssetsImages.eau1,
        AssetsImages.eau2,
        AssetsImages.eau3,
        AssetsImages.eau4,
      ],
      'Woody': [
        AssetsImages.woody1,
        AssetsImages.woody2,
        AssetsImages.woody3,
        AssetsImages.woody4,
      ],
    };

    List<PerfumeModel> perfumes = [];

    // Strong fragrance 类型
    perfumes.addAll([
      PerfumeModel(
        id: 1,
        category: categories[0],
        userId: users[0].id,
        title: 'Midnight Rose',
        description:
            'An intense floral scent with deep rose notes and a hint of spice. The luxurious blend opens with bergamot and black pepper, followed by a heart of Damascus rose and jasmine. The long-lasting base notes of patchouli and amber create an unforgettable aura of elegance.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Strong fragrance']![0],
        cover: null,
        favoriteCount: 189,
        likeCount: 132,
        commentCount: 24,
      ),
      PerfumeModel(
        id: 2,
        category: categories[0],
        userId: users[1].id,
        title: 'Dark Amber',
        description:
            'A bold amber fragrance with smoky undertones and a lasting impression. This opulent perfume combines rich amber with vanilla and benzoin, enhanced by smoky incense and myrrh. The warm base of sandalwood and labdanum creates a mysterious and captivating trail that lingers for hours.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Strong fragrance']![1],
        cover: null,
        favoriteCount: 156,
        likeCount: 95,
        commentCount: 17,
      ),
      PerfumeModel(
        id: 3,
        category: categories[0],
        userId: users[2].id,
        title: 'Velvet Oud',
        description:
            'Luxurious oud wood blended with rich velvet notes for an exotic experience. This intoxicating fragrance opens with saffron and cardamom, revealing a heart of precious oud and Turkish rose. The opulent dry down of vanilla, leather, and musk creates a sensual and sophisticated experience that transports you to ancient Arabian palaces.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Strong fragrance']![2],
        cover: null,
        favoriteCount: 215,
        likeCount: 163,
        commentCount: 28,
      ),
      PerfumeModel(
        id: 4,
        category: categories[0],
        userId: users[3].id,
        title: 'Midnight Elixir',
        description:
            'A mysterious blend of oriental spices with a powerful, captivating presence. This enchanting elixir combines rare spices like cardamom, cinnamon, and clove with precious floral notes of ylang-ylang and jasmine. The rich base of tonka bean, vanilla, and frankincense creates an intoxicating aura that leaves an unforgettable impression wherever you go.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Strong fragrance']![3],
        cover: null,
        favoriteCount: 178,
        likeCount: 124,
        commentCount: 21,
      ),
    ]);

    // Eau de Toilette 类型
    perfumes.addAll([
      PerfumeModel(
        id: 5,
        category: categories[1],
        userId: users[4].id,
        title: 'Fresh Citrus',
        description:
            'A light and refreshing citrus blend, perfect for daytime wear. This invigorating scent opens with bright notes of Sicilian lemon, bergamot, and grapefruit, balanced with green notes of mint and basil. The heart reveals subtle floral accents of lavender and neroli, while the base of white musk provides a clean, lasting finish that is perfect for everyday elegance.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Eau de Toilette']![0],
        cover: null,
        favoriteCount: 142,
        likeCount: 96,
        commentCount: 15,
      ),
      PerfumeModel(
        id: 6,
        category: categories[1],
        userId: users[5].id,
        title: 'Ocean Breeze',
        description:
            'Crisp and clean aquatic notes that evoke a fresh sea breeze. This refreshing fragrance captures the essence of the ocean with marine accords, sea salt, and algae, complemented by citrus notes of mandarin and bergamot. The heart reveals transparent florals and aromatic rosemary, while the base of driftwood and ambergris creates a clean, natural finish that transports you to pristine coastal shores.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Eau de Toilette']![1],
        cover: null,
        favoriteCount: 127,
        likeCount: 89,
        commentCount: 13,
      ),
      PerfumeModel(
        id: 7,
        category: categories[1],
        userId: users[6].id,
        title: 'Morning Dew',
        description:
            'Light floral notes with hints of green tea for a revitalizing experience. This delicate and uplifting fragrance opens with dewy green notes and sparkling bergamot, leading to a heart of jasmine, lily of the valley, and Japanese green tea. The subtle base of white musk and cedarwood provides a clean, crisp finish that evokes the freshness of early morning gardens kissed by dewdrops.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Eau de Toilette']![2],
        cover: null,
        favoriteCount: 135,
        likeCount: 92,
        commentCount: 14,
      ),
      PerfumeModel(
        id: 8,
        category: categories[1],
        userId: users[0].id,
        title: 'Spring Blossom',
        description:
            'A delicate blend of fresh blossoms with a subtle fruity undertone. This joyful fragrance celebrates the arrival of spring with opening notes of pear and apple blossom, leading to a bouquet of peony, magnolia, and cherry blossom at its heart. The gentle base of white amber and cedarwood provides a soft, elegant foundation that captures the ephemeral beauty of flowering trees in the gentle spring sunshine.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Eau de Toilette']![3],
        cover: null,
        favoriteCount: 138,
        likeCount: 94,
        commentCount: 16,
      ),
    ]);

    // Woody 类型
    perfumes.addAll([
      PerfumeModel(
        id: 9,
        category: categories[2],
        userId: users[0].id,
        title: 'Cedar Whisper',
        description:
            'Warm cedar notes with a touch of sandalwood for a sophisticated aura. This refined woody fragrance begins with fresh bergamot and cypress, evolving into a heart of Atlas cedar and aromatic juniper. The rich base of sandalwood, vetiver, and amber creates a warm, comforting embrace that evokes memories of ancient forests and secret woodland paths, perfect for those who appreciate timeless elegance.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Woody']![0],
        cover: null,
        favoriteCount: 165,
        likeCount: 118,
        commentCount: 19,
      ),
      PerfumeModel(
        id: 10,
        category: categories[2],
        userId: users[0].id,
        title: 'Amber Forest',
        description:
            'Rich woody notes combined with amber for a deep, earthy experience. This captivating fragrance opens with spicy notes of cardamom and nutmeg, revealing a complex heart of cedarwood, patchouli, and vetiver. The warm, resinous base of amber, labdanum, and benzoin creates a comforting, enveloping aura that transports you to the depths of an ancient forest bathed in golden afternoon light.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Woody']![1],
        cover: null,
        favoriteCount: 172,
        likeCount: 126,
        commentCount: 22,
      ),
      PerfumeModel(
        id: 11,
        category: categories[2],
        userId: users[1].id,
        title: 'Vetiver Mystique',
        description:
            'Sophisticated blend of vetiver with smoky undertones for an elegant finish. This distinguished fragrance begins with bright citrus notes of grapefruit and bergamot, leading to an aromatic heart of vetiver, geranium, and black pepper. The mysterious base of smoked woods, leather, and tobacco creates a refined and complex character that embodies quiet confidence and timeless masculinity.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Woody']![2],
        cover: null,
        favoriteCount: 186,
        likeCount: 134,
        commentCount: 25,
      ),
      PerfumeModel(
        id: 12,
        category: categories[2],
        userId: users[0].id,
        title: 'Mahogany Noir',
        description:
            'Dark and mysterious woody notes with hints of leather and spice. This intense and sophisticated fragrance opens with black pepper and nutmeg, unfolding to reveal a rich heart of mahogany, cedarwood, and dark leather. The deep base of frankincense, tonka bean, and aged patchouli creates an enigmatic and powerful presence that lingers on the skin, evoking the luxurious atmosphere of an exclusive gentleman club.',
        isRecommend: true,
        isVideo: false,
        url: categoryImages['Woody']![3],
        cover: null,
        favoriteCount: 193,
        likeCount: 139,
        commentCount: 27,
      ),
    ]);

    await SpUtil.setModelList(
      perfumeListKey,
      perfumes.map((e) => e.toJson()).toList(),
    );
  }

  /// 获取所有香水
  static List<PerfumeModel> getAllPerfumes() {
    return SpUtil.getModelList(
      perfumeListKey,
      (json) => PerfumeModel.fromJson(json),
    );
  }

  /// 根据分类获取香水
  static List<PerfumeModel> getPerfumesByCategory(String category) {
    return getAllPerfumes().where((p) => p.category == category).toList();
  }

  /// 新增香水
  static Future<void> addPerfume(PerfumeModel perfume) async {
    List<PerfumeModel> perfumes = getAllPerfumes();
    perfumes.add(perfume);
    await SpUtil.setModelList(
      perfumeListKey,
      perfumes.map((e) => e.toJson()).toList(),
    );
  }

  /// 删除香水
  static Future<void> deletePerfume(int id) async {
    List<PerfumeModel> perfumes = getAllPerfumes();
    perfumes.removeWhere((p) => p.id == id);
    await SpUtil.setModelList(
      perfumeListKey,
      perfumes.map((e) => e.toJson()).toList(),
    );
  }

  /// 更新香水
  static Future<void> updatePerfume(PerfumeModel perfume) async {
    List<PerfumeModel> perfumes = getAllPerfumes();
    int idx = perfumes.indexWhere((p) => p.id == perfume.id);
    if (idx != -1) {
      perfumes[idx] = perfume;
      await SpUtil.setModelList(
        perfumeListKey,
        perfumes.map((e) => e.toJson()).toList(),
      );
    }
  }

  static PerfumeModel getPerfumeById(String id) {
    return getAllPerfumes().firstWhere(
      (perfume) => perfume.id.toString() == id,
      orElse: () => throw Exception('找不到ID为 $id 的香水'),
    );
  }
}
